import React from 'react';
import './maze.scss';
import { api } from 'js/api/api';
import { userData } from 'js/core/userData';
import Progress from 'views/component/progress/progress';
import CollectionProgress from 'views/component/collectionProgress/collectionProgress';
import { panelPop } from 'views/modal/panelPop/panelPop';
import Button from 'views/component/button/button';
import Battle from './battle';
import { browserHistory } from 'react-router';
import SelectTool from './selectTool';
import SelectBloodbottle from './selectBloodbottle';
import iconData from 'js/data/iconData';


//1拾取,2采集,3采矿,4钓鱼,5采伐,6怪物,7副本,8boss,9事件,10npc
let handleText = {
    1: '拾取', 2: '采集', 3: '采伐', 4: '采掘', 5: '钓鱼', 6: '战斗', 7: '战斗', 8: '战斗', 9: '调查', 10: '对话'
};

let cardTypeText = {
    6: '怪物', 7: '副本', 8: 'boss'
};

class Main extends React.Component {
    constructor() {
        super()
        this.state = {
            selectCard: {},
            selectCardIndex: null
        }
    }
    selectCard = (card, cardIndex) => {
        this.setState({ selectCard: card, selectCardIndex: cardIndex })
    }
    pickUp = (cardIndex, itemId) => {
        api('cardPickUp', { index: parseInt(cardIndex), itemId: parseInt(itemId) }, (err, data) => {
            if (data && data.log) {
                window.eventHandle.emit('log', data.log);
            }
            this.setState({})
        });
    }
    cardCollection = (cardIndex) => {
        api('cardCollection', { index: parseInt(cardIndex) }, (err, data) => {
            if (data && data.log) {
                window.eventHandle.emit('log', data.log);
            }
            this.setState({})
        });
    }
    cardFishing = (cardIndex, itemId) => {
        api('cardFishing', { index: parseInt(cardIndex) }, (err, data) => {
            if (data && data.log) {
                window.eventHandle.emit('log', data.log);
            }
            this.setState({})
        });
    }
    mazeForward = () => {
        api('mazeForward', (err, data) => {
            this.setState({})
        });
    }
    cardLeave = (cardIndex) => {
        api('cardLeave', { index: parseInt(cardIndex) }, (err, data) => {
            if (data.log) {
                window.eventHandle.emit('log', data.log);
            }
            if (data.battleMsg) {
                panelPop.showMain(<Battle data={data.battleMsg} />)
            }
            this.setState({ selectCard: {} })
        });
    }
    mazeReset = () => {
        api('mazeReset', (err, data) => {
            if (data.log) {
                window.eventHandle.emit('log', data.log);
            }
            this.setState({})
        });
    }
    goZone = (cardIndex, index) => {
        api('goZone', { index: cardIndex, number: index }, (err, data) => {
            if (data && data.log) {
                window.eventHandle.emit('log', data.log);
            }
            window.eventHandle.emit('updateData');
            this.setState({})
        });
    }
    cardInvestigate = (cardIndex) => {
        api('cardExamine', { index: cardIndex }, (err, data) => {
            if (data && data.log) {
                window.eventHandle.emit('log', data.log);
            }
            this.setState({})
        });
    }
    cardUse = (cardIndex) => {
        api('cardUse', { index: cardIndex }, (err, data) => {
            if (data && data.log) {
                window.eventHandle.emit('log', data.log);
            }
            this.setState({})
        });
    }
    changeMap = () => {
        api('changeMap', { mapType: 3 }, (err, data) => {
            if (data && data.log) {
                window.eventHandle.emit('log', data.log);
            }
            this.setState({})
            browserHistory.push('/town')
        })
    }
    cardBattle = (cardIndex) => {
        api('cardBattle', { index: cardIndex }, (err, data) => {
            if (data && data.log) {
                window.eventHandle.emit('log', data.log);
            }
            panelPop.showMain(<Battle data={data.battleMsg} />)
            this.setState({})
        })
    }
    cardDialogue = (cardIndex) => {
        api('cardDialogue', { index: cardIndex }, (err, data) => {
            if (data && data.log) {
                window.eventHandle.emit('log', data.log);
            }
            this.setState({})
        })
    }
    selectTool = (toolType) => {
        panelPop.showModal(<SelectTool toolType={toolType} complete={() => {
            this.setState({})
        }} />)
    }
    showBag = () => {
        panelPop.showMainBody('bag', {
            beforeClose: () => {
                this.setState({ menuActive: null })
            }
        });
        this.setState({ menuActive: 'bag' })
    }
    showRiskBag = () => {
        panelPop.showMain('riskBag');
    }
    renderCardInfo = (card, cardIndex) => {
        if (!card || !card.type) {
            return
        }
        let totalConfig = window.totalConfig;
        let cardsConfig = totalConfig.card;
        let itemNode = [], handleNode = [], infoNode = [];
        let player = window.player;
        let mazeInfos = player.mazeInfos;
        let mazeId = mazeInfos.mazeId;
        let zoneId = mazeInfos.zoneId;
        let cardId = card.id;
        let cardConfigInfo, cardType;
        if (card.type === 1) {
            cardConfigInfo = cardsConfig[cardId];
            cardType = cardConfigInfo.type;
        }
        if (card.info) {
            let items = card.info.items;
            for (let k = 0; k < items.length; k++) {
                handleNode.push(<div className="pickup-item flex-vcenter" key={items[k][0]}>
                    <div className="name text-center">{propName[items[k][0]]}x{items[k][1]}</div>
                    <div className="pick-button" onClick={() => { this.pickUp(cardIndex, items[k][0]) }}>拾取</div>
                </div>)
            }
        } else {
            if (card.type === 2 || card.type === 3) { //怪物
                handleNode = <CollectionProgress onEnd={() => { this.cardBattle(cardIndex) }}>迎战</CollectionProgress>
            } else {
                if (cardType === 11) {
                    let zoneIds = cardConfigInfo.zoneIds;
                    handleNode = <div className="flex jc-around">{
                        zoneIds.map((id, index) => {
                            return <div className="handle-button" onClick={() => this.goZone(cardIndex, index)} key={id}>前往路口{index + 1}</div>
                        })
                    }</div>
                } else if (cardType === 2 || cardType === 3 || cardType === 4) {
                    let itemId = cardConfigInfo.itemId;
                    handleNode = <CollectionProgress key={itemId} cardType={cardType} action={() => { this.setState({}) }}
                        onEnd={() => { this.cardCollection(cardIndex, itemId) }}>
                        {handleText[cardType]}</CollectionProgress>
                } else if (cardType === 5) {
                    let itemId = cardConfigInfo.itemId;
                    handleNode = <CollectionProgress key={itemId} cardType={cardType} action={() => { this.setState({}) }}
                        onEnd={() => { this.cardFishing(cardIndex, itemId) }}>
                        {handleText[cardType]}</CollectionProgress>
                } else if (cardType === 10) {
                    if (card.info) {
                        let dialogueInfo = info.dialogue;
                        if (dialogueInfo.type === 1) {
                            handleNode.push(<div>{propName[dialogueInfo.taskId]}</div>)
                            handleNode.push(<Button className="leave">接受任务</Button>)
                        } else if (dialogueInfo.type === 2) {
                            for (let value of dialogueInfo.needItems) {
                                handleNode.push(<div>{propName[value[0]]}x{[value[1]]}</div>)
                            }
                            handleNode.push(<CollectionProgress onEnd={() => { this.cardCollection(cardIndex, itemId) }}>给予</CollectionProgress>)
                        }
                    } else {
                        handleNode = <CollectionProgress onEnd={() => this.cardDialogue(cardIndex)}>对话</CollectionProgress>
                    }
                } else if (cardType === 9) {
                    handleNode = <CollectionProgress onEnd={() => { this.cardInvestigate(cardIndex) }}>调查</CollectionProgress>
                } else if (cardType === 12) {
                    if (card.use) {
                        handleNode = <CollectionProgress onEnd={() => this.cardUse(cardIndex)}>喝</CollectionProgress>
                    }
                }
            }
        }

        if (card.type === 2 || card.type === 3) {
            let monsterInfo = window.totalConfig.monster[cardId];
            infoNode.push(<div key={1}>类型:&nbsp;&nbsp;怪物</div>)
            // infoNode.push(<div key={2}>等级:&nbsp;&nbsp;{monsterInfo.fightAttri.lvl}</div>)
            return <div className="cardInfo">
                <div className="cardInfo-name flex-center">{propName[cardId]}</div>
                {/* <div className="cardInfo-desc flex-g-1"></div> */}
                <div className="cardInfo-info">{infoNode}</div>
                <div className="cardInfo-handle flex-col-hcenter">
                    {handleNode}
                </div>
                <div className="flex-center cardInfo-bottom flex-center">
                    <div className="leave-button" onClick={() => this.cardLeave(cardIndex)}>离开</div>
                </div>
            </div>
        } else if (card.type === 4) {
            return <div className="cardInfo">
                <div className="cardInfo-name flex-center">通道口</div>
                <div className="flex-center cardInfo-bottom flex-center">
                    <div className="leave-button" onClick={() => this.cardLeave(cardIndex)}>下一层</div>
                </div>
            </div>
        } else {
            if (cardTypeText[cardType]) {
                infoNode.push(<div key={1}>类型:&nbsp;&nbsp;{cardTypeText[cardType]}</div>)
            }

            if (cardType === 2 || cardType === 3 || cardType === 4) {
                let itemId = cardConfigInfo.itemId;
                infoNode.push(<div key={itemId}>资源:&nbsp;&nbsp;{propName[itemId]}</div>)
            }

            return <div className="cardInfo">
                <div className="cardInfo-name flex-center">{cardConfigInfo.name}</div>
                {/* <div className="cardInfo-desc flex-g-1">{cardConfigInfo.desc}</div> */}
                <div className="cardInfo-info">{infoNode}</div>
                <div className="cardInfo-handle flex-col-hcenter">
                    {handleNode}
                </div>
                <div className="flex-center cardInfo-bottom flex-center">
                    <div className="leave-button" onClick={() => this.cardLeave(cardIndex)}>离开</div>
                </div>
            </div>
        }
    }
    getToolInfo = (item) => {
        if (item) {
            return <div className="flex">
                <div className="toolItemName flex">

                    {window.propName[item.templateId]}
                </div>
                <div className="toolItemHp">{item.hp} </div>
            </div>;
        } else {
            return <div className="toolItemSet">+</div>;
        }
    }
    getBloodbottle = (player) => {
        if (player.bag.bloodbottle) {
            return 'x' + player.bag.bloodbottle.stack;
        } else {
            return 'x0'
        }
    }
    cure = (index) => {
        api('cure', { partnerIndex: index }, () => {
            this.setState({})
        });
    }
    getTeamInfo = () => {
        let player = window.player;
        let battleTeams = player.battleTeams;
        let node = [];
        let fightAttri;
        for (let i = 0; i < 3; i++) {
            let partner = battleTeams[i];
            if (partner) {
                let fightAttri = partner.fightAttri;
                let per = (fightAttri.hp / fightAttri.maxHp * 100) + '%';
                node.push(
                    <div key={i}>
                        <div className="team-name flex-vcenter">
                            <div className={"icon fonts-" + iconData[partner.templateId]}></div>
                            {fightAttri.name}  </div>
                        <div className="flex-vcenter team-item">
                            <div className="hp-par">
                                <div className="hp-text flex">
                                    {/* <div className="icon fonts-heart"></div> */}
                                    <div>{fightAttri.hp}/{fightAttri.maxHp}</div>
                                </div>
                                <div className="hp" style={{ width: per }}></div>
                            </div>
                            <div onClick={() => { this.cure(i) }}>治疗</div>
                        </div>
                    </div>)
            }
        }
        return node;
    }
    setBloodbottle = () => {
        panelPop.show(<SelectBloodbottle complete={() => {
            this.setState({})
        }} />)
    }
    cureAll = () => {
        api('cureAll', () => {
            this.setState({})
        })
    }
    calcAttri = () => {
        api('calcAttri', () => {
            this.setState({})
        })
    }
    render() {
        let { selectCard, selectCardIndex } = this.state;
        let player = window.player;
        let propName = window.propName, totalConfig = window.totalConfig;
        let cardsConfig = totalConfig.card;
        let basicInfo = player.basicInfo;
        let fightAttri = player.fightAttri;
        let mazeInfos = player.mazeInfos;
        let mazeId = mazeInfos.mazeId;
        let zoneId = mazeInfos.zoneId;
        let zoneConfig = totalConfig.maze[mazeId].zones;
        let mazeInfo = player.mazeInfos[mazeId];
        let bag = player.bag;
        let mazeType = mazeInfos.type;
        let cards = mazeInfos.cards;
        return (
            <div id="maze" className="flex-col">
                <div className="cardsMain">
                    <div className="deckMain" onClick={() => { this.mazeReset() }}>
                        {(zoneConfig.cardMaxNumber - mazeInfos.indexId + 1 !== 0) && <div>
                            <div className="deck flex-center">
                                <div className="fonts-cardBg"></div>
                            </div>
                            <div className="deck-number">{zoneConfig.cardMaxNumber - mazeInfos.indexId + 1}</div>
                        </div>}
                    </div>
                    <div>
                        <div className="cards flex">
                            {cards.map((item, index) => {
                                let card = item.card
                                if (card && card.type) {
                                    if (card.type === 4) {
                                        return <div className="flex-g-1" key={card.indexId}>
                                            <div className={"card" + (card.indexId === selectCard.indexId ? ' active' : '')
                                                + (card.type === 3 ? ' copy' : '')}
                                                onClick={() => { this.selectCard(card, index) }}>
                                                <div className="card-name">通道口</div>
                                            </div>
                                        </div>
                                    } else {
                                        return <div className="flex-g-1" key={card.indexId}>
                                            <div className={"card" + (card.indexId === selectCard.indexId ? ' active' : '')
                                                + (card.type === 3 ? ' copy' : '')}
                                                onClick={() => { this.selectCard(card, index) }}>
                                                <div className="card-name">{propName[card.id]}</div>
                                            </div>
                                        </div>
                                    }
                                }
                            })}
                        </div>
                    </div>
                </div>
                <div className="info flex">
                    <div className="playerInfo">
                        <div className="flex jc-center player-status">
                            <div className="flex-g-1 flex ">
                                <div className="player-status-name flex-vcenter">
                                    <div className="icon fonts-tili"></div>
                                    体力
                                </div>
                                <div className="player-status-value">{basicInfo.tili}</div>
                            </div>
                            <div className="flex-g-1 flex">
                                <div className="player-status-name flex-vcenter">
                                    <div className="icon fonts-lucky"></div>
                                    幸运
                                </div>
                                <div className="player-status-value">{basicInfo.lucky}</div>
                            </div>
                        </div>
                        <div className="teamInfo">
                            {this.getTeamInfo()}
                        </div>
                        <div className="adventureBagPanel flex-vcenter">
                            <div className="adventureBag flex-vcenter" onClick={this.showRiskBag}>
                                <div className="fonts fonts-bag"></div>
                                <div>冒险背包</div>
                            </div>
                            <div className="flex-vcenter bloodbottle" onClick={this.setBloodbottle}>
                                <div className="icon fonts-bloodbottle"></div>
                                {this.getBloodbottle(player)}
                                {/* <div className="add-bloodbottle">+</div> */}
                            </div>
                            <div className="" onClick={this.changeMap}>返回</div>
                        </div>
                        <div className="flex">
                            <div onClick={this.cureAll} className="mr5">全体治疗</div><div onClick={this.calcAttri}>重新计算属性</div>
                        </div>
                    </div>

                    <div>
                        <div className="cardInfoMain">
                            {this.renderCardInfo(selectCard, selectCardIndex)}
                        </div>
                        <div className="bottom flex-col-center">
                            {(zoneConfig.cardMaxNumber - mazeInfos.indexId + 1 === 0) && <div className="maze-button maze-leave" onClick={this.changeMap}>返回城镇</div>}
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

export default Main;